{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9de9a93e-9247-4799-a5bb-2ec1575ae8c2",
   "metadata": {},
   "source": [
    "# Live 3D Human Pose Estimation with OpenVINO\n",
    "\n",
    "This notebook demonstrates live 3D Human Pose Estimation with OpenVINO via a webcam. We utilize the model [human-pose-estimation-3d-0001](https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/public/human-pose-estimation-3d-0001) from [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/). At the end of this notebook, you will see live inference results from your webcam (if available). Alternatively, you can also upload a video file to test out the algorithms.\n",
    "**Make sure you have properly installed the [Jupyter extension](https://github.com/jupyter-widgets/pythreejs#jupyterlab) and been using JupyterLab to run the demo as suggested in the `README.md`**\n",
    "\n",
    "> **NOTE**: _To use a webcam, you must run this Jupyter notebook on a computer with a webcam. If you run on a remote server, the webcam will not work. However, you can still do inference on a video file in the final step. This demo utilizes the Python interface in `Three.js` integrated with WebGL to process data from the model inference. These results are processed and displayed in the notebook._\n",
    "\n",
    "_To ensure that the results are displayed correctly, run the code in a recommended browser on one of the following operating systems:_\n",
    "_Ubuntu, Windows: Chrome_\n",
    "_macOS: Safari_\n",
    "\n",
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Prerequisites](#Prerequisites)\n",
    "- [Imports](#Imports)\n",
    "- [The model](#The-model)\n",
    "    - [Download the model](#Download-the-model)\n",
    "    - [Convert Model to OpenVINO IR format](#Convert-Model-to-OpenVINO-IR-format)\n",
    "    - [Select inference device](#Select-inference-device)\n",
    "    - [Load the model](#Load-the-model)\n",
    "- [Processing](#Processing)\n",
    "    - [Model Inference](#Model-Inference)\n",
    "    - [Draw 2D Pose Overlays](#Draw-2D-Pose-Overlays)\n",
    "    - [Main Processing Function](#Main-Processing-Function)\n",
    "- [Run](#Run)\n",
    "\n",
    "\n",
    "### Installation Instructions\n",
    "\n",
    "This is a self-contained example that relies solely on its own code.\n",
    "\n",
    "We recommend  running the notebook in a virtual environment. You only need a Jupyter server to start.\n",
    "For details, please refer to [Installation Guide](https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/README.md#-installation-guide).\n",
    "\n",
    "Make sure your [Jupyter extension](https://github.com/jupyter-widgets/pythreejs#jupyterlab) is working properly.\n",
    "To avoid errors that may arise from the version of the dependency package, it is recommended to use the **JupyterLab** instead of the Jupyter notebook to display image results.\n",
    "```\n",
    "- pip install --upgrade pip && pip install -r requirements.txt\n",
    "- jupyter labextension install --no-build @jupyter-widgets/jupyterlab-manager\n",
    "- jupyter labextension install --no-build jupyter-datawidgets/extension\n",
    "- jupyter labextension install jupyter-threejs\n",
    "- jupyter labextension list\n",
    "```\n",
    "\n",
    "You should see:\n",
    "```\n",
    "JupyterLab v...\n",
    "  ...\n",
    "    jupyterlab-datawidgets v... enabled OK\n",
    "    @jupyter-widgets/jupyterlab-manager v... enabled OK\n",
    "    jupyter-threejs v... enabled OK\n",
    "```\n",
    "\n",
    "<img referrerpolicy=\"no-referrer-when-downgrade\" src=\"https://static.scarf.sh/a.png?x-pxid=5b5a4db0-7875-4bfb-bdbd-01698b5b1a77&file=notebooks/3D-pose-estimation-webcam/3D-pose-estimation.ipynb\" />\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "7925a51b-26ec-43c5-9660-0705c03d724d",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "**The `pythreejs` extension may not display properly when using a Jupyter Notebook release. Therefore, it is recommended to use Jupyter Lab instead.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b84c1f5e-502b-4037-b871-9f84b4e8cef0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import platform\n",
    "\n",
    "if platform.system() == \"Darwin\":\n",
    "    %pip install -q \"numpy<2.0.0\"\n",
    "\n",
    "%pip install pythreejs \"openvino>=2024.4.0\" \"opencv-python\" \"torch==2.8\" \"tqdm\" --extra-index-url https://download.pytorch.org/whl/cpu"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5a9332fb-1cee-4faa-9555-731ddf0e0df7",
   "metadata": {},
   "source": [
    "## Imports\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "316ad889-8514-430f-baf4-4f32abd43356",
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import time\n",
    "from pathlib import Path\n",
    "\n",
    "import cv2\n",
    "import ipywidgets as widgets\n",
    "import numpy as np\n",
    "from IPython.display import clear_output, display\n",
    "import openvino as ov\n",
    "\n",
    "# Fetch `notebook_utils` module\n",
    "import requests\n",
    "\n",
    "if not Path(\"notebook_utils.py\").exists():\n",
    "    r = requests.get(\n",
    "        url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
    "    )\n",
    "    with open(\"notebook_utils.py\", \"w\") as f:\n",
    "        f.write(r.text)\n",
    "\n",
    "if not Path(\"engine3js.py\").exists():\n",
    "    r = requests.get(\n",
    "        url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/engine3js.py\",\n",
    "    )\n",
    "    with open(\"engine3js.py\", \"w\") as f:\n",
    "        f.write(r.text)\n",
    "\n",
    "import notebook_utils as utils\n",
    "import engine3js as engine\n",
    "\n",
    "# Read more about telemetry collection at https://github.com/openvinotoolkit/openvino_notebooks?tab=readme-ov-file#-telemetry\n",
    "from notebook_utils import collect_telemetry\n",
    "\n",
    "collect_telemetry(\"3D-pose-estimation.ipynb\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c96ad61a-59ff-4873-b2f3-3994d6826f51",
   "metadata": {},
   "source": [
    "## The model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "### Download the model\n",
    "[back to top ⬆️](#Table-of-contents:)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "31bd89c7-be8a-4b03-ba38-c19d328e332d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from notebook_utils import download_file\n",
    "import tarfile\n",
    "\n",
    "\n",
    "# directory where model will be downloaded\n",
    "base_model_dir = Path(\"model\")\n",
    "\n",
    "if not base_model_dir.exists():\n",
    "    download_file(\n",
    "        \"https://storage.openvinotoolkit.org/repositories/open_model_zoo/public/2022.1/human-pose-estimation-3d-0001/human-pose-estimation-3d.tar.gz\",\n",
    "        directory=base_model_dir,\n",
    "    )\n",
    "\n",
    "ckpt_file = base_model_dir / \"human-pose-estimation-3d-0001.pth\"\n",
    "\n",
    "if not ckpt_file.exists():\n",
    "    with tarfile.open(base_model_dir / \"human-pose-estimation-3d.tar.gz\") as f:\n",
    "        f.extractall(base_model_dir)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "88f39f76-2f81-4c18-9fda-98ea6a944220",
   "metadata": {},
   "source": [
    "### Convert Model to OpenVINO IR format\n",
    "[back to top ⬆️](#Table-of-contents:)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c9bdfdee-c2ef-4710-96c1-8a6a896a8cba",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "ov_model_path = Path(base_model_dir) / \"human-pose-estimation-3d-0001.xml\"\n",
    "\n",
    "if not ov_model_path.exists():\n",
    "    from model.model import PoseEstimationWithMobileNet\n",
    "\n",
    "    pose_estimation_model = PoseEstimationWithMobileNet(is_convertible_by_mo=True)\n",
    "    pose_estimation_model.load_state_dict(torch.load(ckpt_file, map_location=\"cpu\"))\n",
    "    pose_estimation_model.eval()\n",
    "\n",
    "    with torch.no_grad():\n",
    "        ov_model = ov.convert_model(pose_estimation_model, example_input=torch.zeros([1, 3, 256, 448]), input=[1, 3, 256, 448])\n",
    "        ov.save_model(ov_model, ov_model_path)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "6458fe97-6e93-4357-bc9a-16394d962e56",
   "metadata": {},
   "source": [
    "### Select inference device\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "select device from dropdown list for running inference using OpenVINO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ae27d9b7-95ae-4b1c-acb7-c911ec7f698c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8f9a2502caf645e297617723db3d234d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Device:', index=2, options=('CPU', 'GPU', 'AUTO'), value='AUTO')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "device = utils.device_widget()\n",
    "\n",
    "device"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "986a07ac-d092-4254-848a-dd48f4934fb5",
   "metadata": {},
   "source": [
    "### Load the model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Converted models are located in a fixed structure, which indicates vendor, model name and precision.\n",
    "\n",
    "First, initialize the inference engine, OpenVINO Runtime. Then, read the network architecture and model weights from the `.bin` and `.xml` files to compile for the desired device. An inference request is then created to infer the compiled model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "92a04102-aebf-4976-874b-b98dca97ec48",
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize inference engine\n",
    "core = ov.Core()\n",
    "# read the network and corresponding weights from file\n",
    "model = core.read_model(ov_model_path)\n",
    "# load the model on the specified device\n",
    "compiled_model = core.compile_model(model=model, device_name=device.value)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "48eb5032-a06e-48c1-a3d6-f0fbad9924fb",
   "metadata": {},
   "source": [
    "## Processing\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "### Model Inference\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Frames captured from video files or the live webcam are used as the input for the 3D model. This is how you obtain the output heat maps, PAF (part affinity fields) and features."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "08f8055b-a6cf-4003-8232-6f73a86d6034",
   "metadata": {},
   "outputs": [],
   "source": [
    "def model_infer(scaled_img, stride):\n",
    "    \"\"\"\n",
    "    Run model inference on the input image\n",
    "\n",
    "    Parameters:\n",
    "        scaled_img: resized image according to the input size of the model\n",
    "        stride: int, the stride of the window\n",
    "    \"\"\"\n",
    "\n",
    "    # Remove excess space from the picture\n",
    "    img = scaled_img[\n",
    "        0 : scaled_img.shape[0] - (scaled_img.shape[0] % stride),\n",
    "        0 : scaled_img.shape[1] - (scaled_img.shape[1] % stride),\n",
    "    ]\n",
    "\n",
    "    mean_value = 128.0\n",
    "    scale_value = 255.0\n",
    "\n",
    "    img = (img - mean_value) / scale_value\n",
    "\n",
    "    img = np.transpose(img, (2, 0, 1))[None,]\n",
    "    result = compiled_model(img)\n",
    "    # Get the results\n",
    "    results = (result[0][0], result[1][0], result[2][0])\n",
    "\n",
    "    return results"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "6991403a-4f87-45be-9b3f-d30b23a46dbe",
   "metadata": {},
   "source": [
    "### Draw 2D Pose Overlays\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "We need to define some connections between the joints in advance, so that we can draw the structure of the human body in the resulting image after obtaining the inference results.\n",
    "Joints are drawn as circles and limbs are drawn as lines. The code is based on the [3D Human Pose Estimation Demo](https://github.com/openvinotoolkit/open_model_zoo/tree/master/demos/human_pose_estimation_3d_demo/python) from Open Model Zoo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "22fd3e08-ed3b-44ac-bd07-4a80130d6681",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3D edge index array\n",
    "body_edges = np.array(\n",
    "    [\n",
    "        [0, 1],\n",
    "        [0, 9],\n",
    "        [9, 10],\n",
    "        [10, 11],  # neck - r_shoulder - r_elbow - r_wrist\n",
    "        [0, 3],\n",
    "        [3, 4],\n",
    "        [4, 5],  # neck - l_shoulder - l_elbow - l_wrist\n",
    "        [1, 15],\n",
    "        [15, 16],  # nose - l_eye - l_ear\n",
    "        [1, 17],\n",
    "        [17, 18],  # nose - r_eye - r_ear\n",
    "        [0, 6],\n",
    "        [6, 7],\n",
    "        [7, 8],  # neck - l_hip - l_knee - l_ankle\n",
    "        [0, 12],\n",
    "        [12, 13],\n",
    "        [13, 14],  # neck - r_hip - r_knee - r_ankle\n",
    "    ]\n",
    ")\n",
    "\n",
    "\n",
    "body_edges_2d = np.array(\n",
    "    [\n",
    "        [0, 1],  # neck - nose\n",
    "        [1, 16],\n",
    "        [16, 18],  # nose - l_eye - l_ear\n",
    "        [1, 15],\n",
    "        [15, 17],  # nose - r_eye - r_ear\n",
    "        [0, 3],\n",
    "        [3, 4],\n",
    "        [4, 5],  # neck - l_shoulder - l_elbow - l_wrist\n",
    "        [0, 9],\n",
    "        [9, 10],\n",
    "        [10, 11],  # neck - r_shoulder - r_elbow - r_wrist\n",
    "        [0, 6],\n",
    "        [6, 7],\n",
    "        [7, 8],  # neck - l_hip - l_knee - l_ankle\n",
    "        [0, 12],\n",
    "        [12, 13],\n",
    "        [13, 14],  # neck - r_hip - r_knee - r_ankle\n",
    "    ]\n",
    ")\n",
    "\n",
    "\n",
    "def draw_poses(frame, poses_2d, scaled_img, use_popup):\n",
    "    \"\"\"\n",
    "    Draw 2D pose overlays on the image to visualize estimated poses.\n",
    "    Joints are drawn as circles and limbs are drawn as lines.\n",
    "\n",
    "    :param frame: the input image\n",
    "    :param poses_2d: array of human joint pairs\n",
    "    \"\"\"\n",
    "    for pose in poses_2d:\n",
    "        pose = np.array(pose[0:-1]).reshape((-1, 3)).transpose()\n",
    "        was_found = pose[2] > 0\n",
    "\n",
    "        pose[0], pose[1] = (\n",
    "            pose[0] * frame.shape[1] / scaled_img.shape[1],\n",
    "            pose[1] * frame.shape[0] / scaled_img.shape[0],\n",
    "        )\n",
    "\n",
    "        # Draw joints.\n",
    "        for edge in body_edges_2d:\n",
    "            if was_found[edge[0]] and was_found[edge[1]]:\n",
    "                cv2.line(\n",
    "                    frame,\n",
    "                    tuple(pose[0:2, edge[0]].astype(np.int32)),\n",
    "                    tuple(pose[0:2, edge[1]].astype(np.int32)),\n",
    "                    (255, 255, 0),\n",
    "                    4,\n",
    "                    cv2.LINE_AA,\n",
    "                )\n",
    "        # Draw limbs.\n",
    "        for kpt_id in range(pose.shape[1]):\n",
    "            if pose[2, kpt_id] != -1:\n",
    "                cv2.circle(\n",
    "                    frame,\n",
    "                    tuple(pose[0:2, kpt_id].astype(np.int32)),\n",
    "                    3,\n",
    "                    (0, 255, 255),\n",
    "                    -1,\n",
    "                    cv2.LINE_AA,\n",
    "                )\n",
    "\n",
    "    return frame"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "a6894ce8-ac91-464d-a7f7-54d09f399f4f",
   "metadata": {},
   "source": [
    "### Main Processing Function\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Run 3D pose estimation on the specified source. It could be either a webcam feed or a video file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "3be526d0-75ad-4bd1-85b1-ca8185eca918",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def run_pose_estimation(source=0, flip=False, use_popup=False, skip_frames=0):\n",
    "    \"\"\"\n",
    "    2D image as input, using OpenVINO as inference backend,\n",
    "    get joints 3D coordinates, and draw 3D human skeleton in the scene\n",
    "\n",
    "    :param source:      The webcam number to feed the video stream with primary webcam set to \"0\", or the video path.\n",
    "    :param flip:        To be used by VideoPlayer function for flipping capture image.\n",
    "    :param use_popup:   False for showing encoded frames over this notebook, True for creating a popup window.\n",
    "    :param skip_frames: Number of frames to skip at the beginning of the video.\n",
    "    \"\"\"\n",
    "\n",
    "    focal_length = -1  # default\n",
    "    stride = 8\n",
    "    player = None\n",
    "    skeleton_set = None\n",
    "\n",
    "    try:\n",
    "        # create video player to play with target fps  video_path\n",
    "        # get the frame from camera\n",
    "        # You can skip first N frames to fast forward video. change 'skip_first_frames'\n",
    "        player = utils.VideoPlayer(source, flip=flip, fps=30, skip_first_frames=skip_frames)\n",
    "        # start capturing\n",
    "        player.start()\n",
    "\n",
    "        input_image = player.next()\n",
    "        # set the window size\n",
    "        resize_scale = 450 / input_image.shape[1]\n",
    "        windows_width = int(input_image.shape[1] * resize_scale)\n",
    "        windows_height = int(input_image.shape[0] * resize_scale)\n",
    "\n",
    "        # use visualization library\n",
    "        engine3D = engine.Engine3js(grid=True, axis=True, view_width=windows_width, view_height=windows_height)\n",
    "\n",
    "        if use_popup:\n",
    "            # display the 3D human pose in this notebook, and origin frame in popup window\n",
    "            display(engine3D.renderer)\n",
    "            title = \"Press ESC to Exit\"\n",
    "            cv2.namedWindow(title, cv2.WINDOW_KEEPRATIO | cv2.WINDOW_AUTOSIZE)\n",
    "        else:\n",
    "            # set the 2D image box, show both human pose and image in the notebook\n",
    "            imgbox = widgets.Image(format=\"jpg\", height=windows_height, width=windows_width)\n",
    "            display(widgets.HBox([engine3D.renderer, imgbox]))\n",
    "\n",
    "        skeleton = engine.Skeleton(body_edges=body_edges)\n",
    "\n",
    "        processing_times = collections.deque()\n",
    "\n",
    "        while True:\n",
    "            # grab the frame\n",
    "            frame = player.next()\n",
    "            if frame is None:\n",
    "                print(\"Source ended\")\n",
    "                break\n",
    "\n",
    "            # resize image and change dims to fit neural network input\n",
    "            # (see https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/public/human-pose-estimation-3d-0001)\n",
    "            scaled_img = cv2.resize(frame, dsize=(model.inputs[0].shape[3], model.inputs[0].shape[2]))\n",
    "\n",
    "            if focal_length < 0:  # Focal length is unknown\n",
    "                focal_length = np.float32(0.8 * scaled_img.shape[1])\n",
    "\n",
    "            # inference start\n",
    "            start_time = time.time()\n",
    "            # get results\n",
    "            inference_result = model_infer(scaled_img, stride)\n",
    "\n",
    "            # inference stop\n",
    "            stop_time = time.time()\n",
    "            processing_times.append(stop_time - start_time)\n",
    "            # Process the point to point coordinates of the data\n",
    "            poses_3d, poses_2d = engine.parse_poses(inference_result, 1, stride, focal_length, True)\n",
    "\n",
    "            # use processing times from last 200 frames\n",
    "            if len(processing_times) > 200:\n",
    "                processing_times.popleft()\n",
    "\n",
    "            processing_time = np.mean(processing_times) * 1000\n",
    "            fps = 1000 / processing_time\n",
    "\n",
    "            if len(poses_3d) > 0:\n",
    "                # From here, you can rotate the 3D point positions using the function \"draw_poses\",\n",
    "                # or you can directly make the correct mapping below to properly display the object image on the screen\n",
    "                poses_3d_copy = poses_3d.copy()\n",
    "                x = poses_3d_copy[:, 0::4]\n",
    "                y = poses_3d_copy[:, 1::4]\n",
    "                z = poses_3d_copy[:, 2::4]\n",
    "                poses_3d[:, 0::4], poses_3d[:, 1::4], poses_3d[:, 2::4] = (\n",
    "                    -z + np.ones(poses_3d[:, 2::4].shape) * 200,\n",
    "                    -y + np.ones(poses_3d[:, 2::4].shape) * 100,\n",
    "                    -x,\n",
    "                )\n",
    "\n",
    "                poses_3d = poses_3d.reshape(poses_3d.shape[0], 19, -1)[:, :, 0:3]\n",
    "                people = skeleton(poses_3d=poses_3d)\n",
    "\n",
    "                try:\n",
    "                    engine3D.scene_remove(skeleton_set)\n",
    "                except Exception:\n",
    "                    pass\n",
    "\n",
    "                engine3D.scene_add(people)\n",
    "                skeleton_set = people\n",
    "\n",
    "                # draw 2D\n",
    "                frame = draw_poses(frame, poses_2d, scaled_img, use_popup)\n",
    "\n",
    "            else:\n",
    "                try:\n",
    "                    engine3D.scene_remove(skeleton_set)\n",
    "                    skeleton_set = None\n",
    "                except Exception:\n",
    "                    pass\n",
    "\n",
    "            cv2.putText(\n",
    "                frame,\n",
    "                f\"Inference time: {processing_time:.1f}ms ({fps:.1f} FPS)\",\n",
    "                (10, 30),\n",
    "                cv2.FONT_HERSHEY_COMPLEX,\n",
    "                0.7,\n",
    "                (0, 0, 255),\n",
    "                1,\n",
    "                cv2.LINE_AA,\n",
    "            )\n",
    "\n",
    "            if use_popup:\n",
    "                cv2.imshow(title, frame)\n",
    "                key = cv2.waitKey(1)\n",
    "                # escape = 27, use ESC to exit\n",
    "                if key == 27:\n",
    "                    break\n",
    "            else:\n",
    "                # encode numpy array to jpg\n",
    "                imgbox.value = cv2.imencode(\n",
    "                    \".jpg\",\n",
    "                    frame,\n",
    "                    params=[cv2.IMWRITE_JPEG_QUALITY, 90],\n",
    "                )[1].tobytes()\n",
    "\n",
    "            engine3D.renderer.render(engine3D.scene, engine3D.cam)\n",
    "\n",
    "    except KeyboardInterrupt:\n",
    "        print(\"Interrupted\")\n",
    "    except RuntimeError as e:\n",
    "        print(e)\n",
    "    finally:\n",
    "        clear_output()\n",
    "        if player is not None:\n",
    "            # stop capturing\n",
    "            player.stop()\n",
    "        if use_popup:\n",
    "            cv2.destroyAllWindows()\n",
    "        if skeleton_set:\n",
    "            engine3D.scene_remove(skeleton_set)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "344840a6-9660-4a11-8b05-729ac2969e28",
   "metadata": {},
   "source": [
    "## Run\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Run, using a webcam as the video input. By default, the primary webcam is set with `source=0`. If you have multiple webcams, each one will be assigned a consecutive number starting at 0. Set `flip=True` when using a front-facing camera. Some web browsers, especially Mozilla Firefox, may cause flickering. If you experience flickering, set `use_popup=True`.\n",
    "\n",
    "> **NOTE**:\n",
    ">\n",
    "> *1. To use this notebook with a webcam, you need to run the notebook on a computer with a webcam. If you run the notebook on a server (e.g. Binder), the webcam will not work.*\n",
    ">\n",
    "> *2. Popup mode may not work if you run this notebook on a remote computer (e.g. Binder).*\n",
    "\n",
    "If you do not have a webcam, you can still run this demo with a video file. Any [format supported by OpenCV](https://docs.opencv.org/4.5.1/dd/d43/tutorial_py_video_display.html) will work."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d2d1a143-afcb-4f22-a4cc-657a080b70bf",
   "metadata": {},
   "source": [
    "Using the following method, you can click and move your mouse over the picture on the left to interact."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3f82e298-5912-48c7-90b5-339aea3c177d",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9110833919d0455cb2b49b292c79fea1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(Renderer(camera=PerspectiveCamera(aspect=1.7786561264822134, position=(300.0, 100.0, 0.0), proj…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from notebook_utils import download_file\n",
    "\n",
    "USE_WEBCAM = False\n",
    "\n",
    "cam_id = 0\n",
    "if not Path(\"face-demographics-walking.mp4\").exists():\n",
    "    download_file(\n",
    "        \"https://storage.openvinotoolkit.org/data/test_data/videos/face-demographics-walking.mp4\",\n",
    "    )\n",
    "video_path = \"face-demographics-walking.mp4\"\n",
    "\n",
    "source = cam_id if USE_WEBCAM else video_path\n",
    "\n",
    "run_pose_estimation(source=source, flip=isinstance(source, int), use_popup=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  },
  "openvino_notebooks": {
   "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/notebooks/3D-pose-estimation-webcam/3D-pose-estimation.gif?raw=true",
   "tags": {
    "categories": [
     "Live Demos"
    ],
    "libraries": [],
    "other": [],
    "tasks": [
     "Pose Estimation"
    ]
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
